package kgc.crm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import kgc.crm.mapper.UserRoleMapper;
import kgc.crm.model.Role;
import kgc.crm.model.RoleMenu;
import kgc.crm.model.UserRole;
import kgc.crm.service.IUserRoleService;
import kgc.crm.service.IUserService;
import kgc.crm.util.EmptyChecker;
import kgc.crm.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
@Slf4j
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper,UserRole> implements IUserRoleService {
    @Override
    public ResponseEntity associate(Integer roleId, String userIds) {
        if (EmptyChecker.isEmpty(roleId)) {
            //拿到的用户为空的话
            log.error("【角色模块】关联员工，role对象ID不能为空", roleId);
            return ResultUtil.error("关联失败");
        }
        if (EmptyChecker.isEmpty(userIds)) {
            log.error("【角色模块】关联员工，参数不能为空");
            return ResultUtil.error("关联失败");
        }
        JSONObject object = JSON.parseObject(userIds);
        JSONArray array = object.getJSONArray("ids");
        ArrayList<UserRole> list = new ArrayList();
        for (int i = 0; i < array.size(); i++) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            //Long.valueOf()把字符串转成Long
            userRole.setUserId(Long.parseLong(array.get(i).toString()));
            list.add(userRole);
        }
        boolean batch;
        //saveBatch 批量添加
        //把获取到的JSONArray array数组存到Userrole对象中
        //存的时候先把array每一个的值转成String再强转成Long类型的
        //然后再把存好的UserRole对象存到创建的ArrayList集合中
        try {
            batch = saveBatch(list, array.size());
        } catch (Exception e) {
            log.error("【角色模块】关联员工，sql语句执行错误", e);
            return ResultUtil.error("关联失败");
        }
        if (!batch) {
            log.error("【角色模块】关联员工，添加不成功");
            return ResultUtil.error("关联失败");
        }
        return ResultUtil.success(list);
    }

}

